﻿using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RBAC.Api.Demain.Entities;
using RBAC.Api.Erroc;
using RBAC.Api.Read.Command.RBAC;
using RBAC.Api.Read.Dto;
using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace RBAC.Api.Read.Controllers
{
    /// <summary>
    /// 管理员控制器--读
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class ManagerController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<ManagerController> _logger;

        public ManagerController(IMediator mediator, ILogger<ManagerController> logger)
        {
            this.mediator = mediator;
            this._logger = logger;
        }
        /// <summary>
        /// 获取权限列表
        /// </summary>
        /// <param name="permissionName">权限名称</param>
        /// <param name="pageIndex">页数</param>
        /// <param name="pageSize">条数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPagin<Permission>>> GetPermission(string? permissionName, int pageIndex, int pageSize)
        {
            var stopwatch = Stopwatch.StartNew();
            _logger.LogInformation("开始处理获取权限列表请求: 权限名称={PermissionName}, 页数={PageIndex}, 条数={PageSize}", 
                permissionName, pageIndex, pageSize);
            
            try
            {
                GetPressionCommand command = new GetPressionCommand();
                command.PermissionName = permissionName;
                command.PageIndex = pageIndex;
                command.PageSize = pageSize;
                var result = await mediator.Send(command);
                _logger.LogInformation("获取权限列表请求处理成功");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取权限列表请求处理异常: {Message}", ex.Message);
                return new APIResult<APIPagin<Permission>> 
                { 
                    Code = ResultCode.Fail, 
                    Message = $"获取权限列表失败: {ex.Message}" 
                };
            }
            finally
            {
                stopwatch.Stop();
                _logger.LogInformation("获取权限列表请求处理完成，耗时: {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds);
            }
        }
       /// <summary>
       /// 获取角色权限列表
       /// </summary>
       /// <param name="roleName">角色名称</param>
       /// <param name="pageIndex">页数</param>
       /// <param name="pageSize">条数</param>
       /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPagin<RoleDto>>> GetRole(string? roleName, int pageIndex, int pageSize)
        {
            var stopwatch = Stopwatch.StartNew();
            _logger.LogInformation("开始处理获取角色权限列表请求: 角色名称={RoleName}, 页数={PageIndex}, 条数={PageSize}", 
                roleName, pageIndex, pageSize);
            
            try
            {
                GetRoleCommand command = new GetRoleCommand();
                command.RoleName = roleName;
                command.PageIndex = pageIndex;
                command.PageSize = pageSize;
                var result = await mediator.Send(command);
                _logger.LogInformation("获取角色权限列表请求处理成功");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取角色权限列表请求处理异常: {Message}", ex.Message);
                return new APIResult<APIPagin<RoleDto>> 
                { 
                    Code = ResultCode.Fail, 
                    Message = $"获取角色权限列表失败: {ex.Message}" 
                };
            }
            finally
            {
                stopwatch.Stop();
                _logger.LogInformation("获取角色权限列表请求处理完成，耗时: {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds);
            }
        }
        /// <summary>
        /// 获取用户角色列表
        /// </summary>
        /// <param name="userName">用户名称</param>
        /// <param name="pageIndex">页数</param>
        /// <param name="pageSize">条数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<APIPagin<UserDto>>> GetUser(string? name, int pageIndex, int pageSize)
        {
            var stopwatch = Stopwatch.StartNew();
            _logger.LogInformation("开始处理获取用户角色列表请求: 用户名称={Name}, 页数={PageIndex}, 条数={PageSize}", 
                name, pageIndex, pageSize);
            
            try
            {
                GetUserCommand command = new GetUserCommand();
                command.Name = name;
                command.PageIndex = pageIndex;
                command.PageSize = pageSize;
                var result = await mediator.Send(command);
                _logger.LogInformation("获取用户角色列表请求处理成功");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户角色列表请求处理异常: {Message}", ex.Message);
                return new APIResult<APIPagin<UserDto>> 
                { 
                    Code = ResultCode.Fail, 
                    Message = $"获取用户角色列表失败: {ex.Message}" 
                };
            }
            finally
            {
                stopwatch.Stop();
                _logger.LogInformation("获取用户角色列表请求处理完成，耗时: {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds);
            }
        }
        /// <summary>
        /// 动态菜单权限
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<CascadeItem>>> GetCascadeItem([FromQuery] GetMenuPermissionCommand request)
        {
            var stopwatch = Stopwatch.StartNew();
            _logger.LogInformation("开始处理获取动态菜单权限请求");
            
            try
            {
                var result = await mediator.Send(request);
                _logger.LogInformation("获取动态菜单权限请求处理成功");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取动态菜单权限请求处理异常: {Message}", ex.Message);
                return new APIResult<List<CascadeItem>> 
                { 
                    Code = ResultCode.Fail, 
                    Message = $"获取动态菜单权限失败: {ex.Message}" 
                };
            }
            finally
            {
                stopwatch.Stop();
                _logger.LogInformation("获取动态菜单权限请求处理完成，耗时: {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds);
            }
        }
        /// <summary>
        /// 获取权限列表中
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<Permission>>> GetPermissionses()
        {
            var stopwatch = Stopwatch.StartNew();
            _logger.LogInformation("开始处理获取权限列表请求");
            
            try
            {
                PermissionQueryCommand command = new PermissionQueryCommand();
                var result = await mediator.Send(command);
                _logger.LogInformation("获取权限列表请求处理成功");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取权限列表请求处理异常: {Message}", ex.Message);
                return new APIResult<List<Permission>> 
                { 
                    Code = ResultCode.Fail, 
                    Message = $"获取权限列表失败: {ex.Message}" 
                };
            }
            finally
            {
                stopwatch.Stop();
                _logger.LogInformation("获取权限列表请求处理完成，耗时: {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds);
            }
        }
        /// <summary>
        /// 获取角色列表中
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<APIResult<List<Role>>> GetRoles()
        {
            var stopwatch = Stopwatch.StartNew();
            _logger.LogInformation("开始处理获取角色列表请求");
            
            try
            {
                RoleQueryCommand command = new RoleQueryCommand();
                var result = await mediator.Send(command);
                _logger.LogInformation("获取角色列表请求处理成功");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取角色列表请求处理异常: {Message}", ex.Message);
                return new APIResult<List<Role>> 
                { 
                    Code = ResultCode.Fail, 
                    Message = $"获取角色列表失败: {ex.Message}" 
                };
            }
            finally
            {
                stopwatch.Stop();
                _logger.LogInformation("获取角色列表请求处理完成，耗时: {ElapsedMilliseconds}ms", stopwatch.ElapsedMilliseconds);
            }
        }
    }
}
